package com.detu.ivos.dictoption.service.impl;

import com.detu.ivos.base.exception.ServiceException;
import com.detu.ivos.base.response.StatusCode;
import com.detu.ivos.dict.mapper.DictMapper;
import com.detu.ivos.dict.pojo.dto.DictQuery;
import com.detu.ivos.dict.pojo.entity.Dict;
import com.detu.ivos.dict.pojo.vo.DictVO;
import com.detu.ivos.dictoption.mapper.DictOptionMapper;
import com.detu.ivos.dictoption.pojo.dto.DictOptionQuery;
import com.detu.ivos.dictoption.pojo.dto.DictOptionSaveParam;
import com.detu.ivos.dictoption.pojo.entity.DictOption;
import com.detu.ivos.dictoption.pojo.vo.DictOptionVO;
import com.detu.ivos.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class DictOptionServiceImpl implements DictOptionService {
    @Autowired
    DictOptionMapper dictOptionMapper;
    @Autowired
    DictMapper dictMapper;
    @Override
    public List<DictOptionVO> select(DictOptionQuery dictOptionQuery) {
        log.debug("业务成查询的字典ID{}",dictOptionQuery);
        List<DictOptionVO> dictOptionVOS=dictOptionMapper.selectByDictId(dictOptionQuery);
        return dictOptionVOS;
    }

    @Override
    public void insertDictOption(DictOptionSaveParam dictOptionSaveParam) {
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionSaveParam,dictOption);
        if (dictOption.getId()==null){
            dictOption.setCreateTime(new Date());
            int i=dictOptionMapper.insertDictOption(dictOption);
        }else{
            dictOption.setUpdateTime(new Date());
            int i=dictOptionMapper.updateDictOption(dictOption);
        }

    }

    @Override
    public void deleteById(DictOptionSaveParam dictOptionSaveParam) {
        dictOptionMapper.deleteDictOptionById(dictOptionSaveParam.getId());
        log.debug("业务层中删除的字典项id={}",dictOptionSaveParam.getId());
    }

    @Override
    public List<DictOptionVO> selectDictOptionByCode(String code) {
        log.debug("根据字典code查询字典项：code:={}",code);
        DictQuery dictQuery =new DictQuery();
        dictQuery.setCode(code);
        List<DictVO> selectDictVO = dictMapper.select(dictQuery);
        if (selectDictVO.size()>=0 && selectDictVO!=null){
            DictVO dictVO=selectDictVO.get(0);
            log.debug("根据字典code查询字典项id={}",dictVO.getId());
            DictOptionQuery dictOptionQuery = new DictOptionQuery();
            dictOptionQuery.setDictId(dictVO.getId());
            List<DictOptionVO> dictOptionVOS
                    = dictOptionMapper.selectByDictId(dictOptionQuery);
            return dictOptionVOS;
        }else{
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }

    }
}
